/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.screw.engine;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import lombok.Getter;
import org.elsfs.cloud.common.util.exception.ProduceException;
import org.elsfs.cloud.common.util.lang.Assert;

/**
 * 生成构造工厂
 *
 * @author SanLi Created by qinggang.zuo@gmail.com / 2689170096@qq.com on 2020/3/21 21:20
 */
@Getter
public class EngineFactory {
  /** EngineConfig */
  private EngineConfig engineConfig;

  public EngineFactory(EngineConfig configuration) {
    Assert.notNull(configuration, "EngineConfig can not be empty!");
    this.engineConfig = configuration;
  }

  private EngineFactory() {}

  /**
   * 获取配置的数据库类型实例
   *
   * @return {@link TemplateEngine} 数据库查询对象
   */
  public TemplateEngine newInstance() {
    try {
      // 获取实现类
      Class<? extends TemplateEngine> query = this.engineConfig.getProduceType().getImplClass();
      // 获取有参构造
      Constructor<? extends TemplateEngine> constructor = query.getConstructor(EngineConfig.class);
      // 实例化
      return constructor.newInstance(engineConfig);
    } catch (InstantiationException
        | IllegalAccessException
        | NoSuchMethodException
        | InvocationTargetException e) {
      throw new ProduceException(e);
    }
  }
}
